//
//  ServiceManager.m
//  Cabs
//
//  Created by Joey on 2018/5/15.
//  Copyright © 2018年 Happyev. All rights reserved.
//

#import "ServiceManager.h"

@implementation AFHTTPSessionManager (Manager)

+ (instancetype)shareManager {
    static AFHTTPSessionManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        NSLog(@"%@",Main_Token_Model_MANAGER.RootUrl);
        
        manager = [[self manager]initWithBaseURL:[NSURL URLWithString:Main_Token_Model_MANAGER.RootUrl]];
        
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.requestSerializer.timeoutInterval = NetTimeoutInterval;
        [manager jwxSecurity];
    });
    return manager;
}

-(void)jwxSecurity {

    // /先导入证书
    // 使用证书文件

    NSString *path = @"";
    if ([Main_Token_Model_MANAGER.RootUrl rangeOfString:@"release.ms1968"].location !=NSNotFound) {
        path = @"1_release.ms1968.com_bundle";
    }else if ([Main_Token_Model_MANAGER.RootUrl rangeOfString:@"api.cztec"].location !=NSNotFound){
        path = @"1_api.cztec.com_bundle";

    }else {
        return ;
    }
    
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:path ofType:@"cer"];//证书的路径
    NSData *certData = [NSData dataWithContentsOfFile:cerPath];

    // 使用字符串

    // AFSSLPinningModeCertificate 使用证书验证模式
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    
    // allowInvalidCertificates 是否允许无效证书（也就是自建的证书），默认为NO
    // 如果是需要验证自建证书，需要设置为YES
    securityPolicy.allowInvalidCertificates = YES;
    
    //validatesDomainName 是否需要验证域名，默认为YES；
    //假如证书的域名与你请求的域名不一致，需把该项设置为NO；如设成NO的话，即服务器使用其他可信任机构颁发的证书，也可以建立连接，这个非常危险，建议打开。
    //置为NO，主要用于这种情况：客户端请求的是子域名，而证书上的是另外一个域名。因为SSL证书上的域名是独立的，假如证书上注册的域名是www.google.com，那么mail.google.com是无法验证通过的；当然，有钱可以注册通配符的域名*.google.com，但这个还是比较贵的。
    //如置为NO，建议自己添加对应域名的校验逻辑。
    securityPolicy.validatesDomainName = YES;
    
    securityPolicy.pinnedCertificates = [NSSet setWithObject:certData];
    
    self.securityPolicy = securityPolicy;

}

@end


@implementation ServiceManager

+ (void)cancelAllRequest {
    //拿到单利
    AFHTTPSessionManager *manager = [AFHTTPSessionManager shareManager];
    //取消之前的所有任务
    [manager.tasks makeObjectsPerformSelector:@selector(cancel)];
}

//请求
//请求
+ (RACSignal *)postWithUrl:(NSString *)url param:(NSDictionary *)param reponseObjctClass:(Class)reponseObjctClass{
    
    NSString *urlString = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager shareManager];
    
    //    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", @"application/javascript",@"application/json", @"application/x-www-form-urlencoded", nil]];
    
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];

    

    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    [manager.requestSerializer setValue:kUSER_INFO_MANAGER.token forHTTPHeaderField:@"Authorization"];

    [manager.requestSerializer setValue:kHEADERS_VALUE forHTTPHeaderField:kHEADERS_KEY];

    RACSubject *subject = [RACSubject subject];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [manager POST:urlString parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        //        id responseData = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        id responseData = responseObject;
//        NSLog(@"%@",[ServiceManager convertToJsonData1:responseObject]);
        [subject sendNext:[ResponseData responseDataWithData:responseData reponseObjctClass:reponseObjctClass]];
        
        [subject sendCompleted];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
        ResponseData *responseData = [ResponseData responseDataWithError:error];
        
        [subject sendNext:responseData];
        
        [subject sendCompleted];
        
    }];
    return subject;
}




+ (RACSignal *)getWithUrl:(NSString *)url param:(NSDictionary *)param reponseObjctClass:(Class)reponseObjctClass{
    
    NSString *urlString = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager shareManager];
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:kUSER_INFO_MANAGER.token forHTTPHeaderField:@"Authorization"];

    RACSubject *subject = [RACSubject subject];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    [manager GET:urlString parameters:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        //        id responseData = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        id responseData = responseObject;
        
//        NSLog(@"%@",[ServiceManager convertToJsonData1:responseObject]);
        [subject sendNext:[ResponseData responseDataWithData:responseData reponseObjctClass:reponseObjctClass]];
        
        [subject sendCompleted];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
        ResponseData *responseData = [ResponseData responseDataWithError:error];
        
        [subject sendNext:responseData];
        
        [subject sendCompleted];
        
    }];
    
    
    return subject;
}
+(NSString *)convertToJsonData1:(NSDictionary *)dict

{
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
        NSLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0,jsonString.length};
    
    //去掉字符串中的空格
    
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
    
}
+ (RACSignal *)deleteWithUrl:(NSString *)url param:(NSDictionary *)param Api_key:(NSString*)api_key reponseObjctClass:(Class)reponseObjctClass{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json",@"text/javascript",@"text/json",@"text/plain", nil];
    
    // 设置请求头
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:api_key forHTTPHeaderField:@"api_key"];

    RACSubject *subject = [RACSubject subject];
    
    [manager DELETE:url parameters:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        id responseData = responseObject;
        
        [subject sendNext:[ResponseData responseDataWithData:responseData reponseObjctClass:reponseObjctClass]];
        
        [subject sendCompleted];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
        ResponseData *responseData = [ResponseData responseDataWithError:error];
        
        [subject sendNext:responseData];
        
        [subject sendCompleted];
        
    }];
    return subject;
}





+ (RACSignal *)requestWithUrl:(NSString *)url param:(NSDictionary *)param reponseObjctClass:(Class)reponseObjctClass{
    
    NSString *urlString = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager shareManager];
    
    //    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", @"application/javascript",@"application/json", @"application/x-www-form-urlencoded", nil]];
    //
    manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    //        [manager.requestSerializer setValue:kHEADERS_VALUE forHTTPHeaderField:kHEADERS_KEY];

    RACSubject *subject = [RACSubject subject];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    if([url rangeOfString:@"?"].location !=NSNotFound)
    {
        NSLog(@"get请求");
        [manager GET:urlString parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [ServiceManager managerSuccess:responseObject];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [ServiceManager managerError:error];
        }];
    }
    else
    {
        NSLog(@"post 请求");
        [manager POST:urlString parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            [ServiceManager managerSuccess:responseObject];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [ServiceManager managerError:error];
            
        }];
    }
    
    
    
    
    return subject;
}

+(void)managerSuccess:(id)responseObject{
    RACSubject *subject = [RACSubject subject];
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    id responseData = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
    /* TODO: ================= 网络请求封装 =================*/
    
    //    [subject sendNext:[ResponseData responseDataWithData:responseData]];
    //        [subject sendNext:[ResponseData responseDataWithData:responseData reponseObjctClass:reponseObjctClass]];
    
    [subject sendCompleted];
}

+(void)managerError:(NSError*)error{
    RACSubject *subject = [RACSubject subject];
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    
    ResponseData *responseData = [ResponseData responseDataWithError:error];
    
    [subject sendNext:responseData];
    
    [subject sendCompleted];
}


@end

